package com.mcb_wxc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcb_wxc.config.SysConfigure;
import com.mcb_wxc.entity.vo.SendTemplateMessage;
import com.mcb_wxc.entity.vo.TemplateData;
import com.mcb_wxc.http.HttpRequester;
import com.mcb_wxc.http.HttpRespons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 小生
 * 2019/1/18 8:59.
 */
@Slf4j
public class WxApplyUtil {
    @Autowired
    SysConfigure sysConfigure;
    public static Map<String, Object> templateApply(String appid, String secret, String formId, Map<String,TemplateData> data) {
        Map<String, Object> datamap = null;
        try {
            String accessToken = getConfigureAccessToken(appid,secret);
            SendTemplateMessage sendTemplateMessage = new SendTemplateMessage();
            sendTemplateMessage.setTouser("o6B0c0cq0eDcv_3ZgqkvPY-GGXdE");
            sendTemplateMessage.setTemplate_id("4WgknwkUKos2ufLHWvqVcnppQyx3o3qMyZGNfkvkI7w");
            sendTemplateMessage.setForm_id(formId);
            sendTemplateMessage.setData(data);
            String json = JSONObject.toJSONString(sendTemplateMessage);
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken;
            HttpRequester http = new HttpRequester();
            String respons = http.sendPost(url,json);

            log.info("##模版发送JSON数据:  "+json);
            datamap = JSON.parseObject(respons);
        }catch (Exception e) {
            log.error("获取accessToken异常" + e.getMessage());
        }
        return datamap;
    }

    /**
     * 获取AccessToken并保存到配置文件 设置过期时间为7000秒
     * @param appid
     * @param secret
     */
    private static String getConfigureAccessToken(String appid, String secret) {
        String currentDateStr = DateFormatUtil.formatDateForSec(new Date());
        String accessToken = null;
        //获取配置文件的过期时间
        String expiresTime = PropertiesUtil.readData("accessToken.properties", "expiresTime");
        //过期时间为空 或者 过期时间小于当前时间 就重新获取
        if(expiresTime == null || DateFormatUtil.compareTimeSec(expiresTime,currentDateStr)) {
            Map<String, Object> resultMap = getAccessToken(appid, secret);
            /*写道配置文件*/
            accessToken = resultMap.get("access_token") + "";
            String date = DateFormatUtil.secondMove(currentDateStr,7000);
            PropertiesUtil.writeData("accessToken.properties", "accessToken",accessToken);
            PropertiesUtil.writeData("accessToken.properties", "expiresTime", date);
        } else { //直接读配置文件
            accessToken = PropertiesUtil.readData("accessToken.properties", "accessToken");
        }
        return accessToken;
    }

    /**
     * 直接请求小程序接口获取accessToken
     * @param appid
     * @param secret
     * @return
     */
    private static Map<String, Object> getAccessToken(String appid, String secret){
        Map<String, Object> datamap = null;
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpRequester http = new HttpRequester();
            HttpRespons respons = http.sendGet(url);
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(respons.getContent()); // 转换成JSONObject对象
            datamap = jsonObject;
        } catch (IOException e) {
            log.error("获取accessToken异常" + e.getMessage());
        }
        return datamap;
    }

    public static void main(String[] args) {
        //getConfigureAccessToken("wxfd753794e86d02d8","f2d78f39bc9f0bb9c2b415c25ae3773d");
        Map<String,TemplateData> map = new HashMap<>();
        map.put("keyword1",new TemplateData("我叫你一声你敢答应吗"));
        map.put("keyword2",new TemplateData("行者孙"));
        map.put("keyword1",new TemplateData("我叫你一声你敢答应吗"));
        map.put("keyword2",new TemplateData("行者孙"));
        templateApply("wxfd753794e86d02d8","f2d78f39bc9f0bb9c2b415c25ae3773d","1547796207489",map);
    }
}
